<!-- 修改权限 -->
<template>
  <div class="modifyPermission">
    <a-form-model
      ref="ruleForm"
      :model="form"
      :rules="rules"
      :label-col="{ span: 2 }"
      :wrapper-col="{ span: 20 }"
    >
      <a-form-model-item
        label="角色名称"
        prop="name"
      >
        <a-input
          placeholder="请选择角色名称"
          style="width:260px"
          v-model="form.name"
        />
      </a-form-model-item>

      <a-form-model-item
        label="选择权限"
        prop="name"
      >
        <a-tree
          v-model="form.permissionIdList"
          checkable
          :tree-data="treeData"
        />
      </a-form-model-item>
      <a-form-model-item>
        <a-row>
          <a-col :offset="2">
            <a-button
              class="m-r-20"
              @click="$router.push({path:'/setting/permission'})"
            >
              取消
            </a-button>
            <a-button
              type="primary"
              @click="submit"
            >
              保存
            </a-button>
          </a-col>
        </a-row>

      </a-form-model-item>
    </a-form-model>

  </div>
</template>

<script>
export default {
  name: 'modifyPermission',
  data () {
    return {
      form: {
        permissionIdList: [],
        name: undefined,
      },
      rules: {
        name: [
          { required: true, message: '请选择角色名称', trigger: 'blur' },
        ],
        permissionIdList: [
          { required: true, message: '请选择权限', trigger: 'blur' },
        ],
      },
      treeData: [],
      originData: [],  //原始数据
      roleId: ''
    };
  },
  computed: {
  },
  watch: {
    permissionIdList (val) {
      console.log('onCheck', val);
    },
  },
  async mounted () {
    this.roleId = this.$route.query.id
    await this.permissionList()
    this.roleId &&this.getSelectedRole()
  },
  methods: {
    getSelectedRole () {
      this.$axios({
        url: '/role',
        method: 'get',
        loadingEl: this.$el,
        cancel: {
          _self: this
        },
        params: {
          id: this.roleId
        }
      }).then(res => {
        console.log(res.data);
        this.form.name = res.data.name
        this.form.permissionIdList = this.parsingRoleId(res.data.permissionList)
      })
    },
    //权限列表
    async permissionList () {
      await this.$axios({
        url: 'permission/list',
        method: 'get',
        loadingEl: this.$el,
        cancel: {
          _self: this
        },
      }).then(res => {
        let permissionList = res.data && res.data.permissionList || []
        this.originData = permissionList
        this.treeData = this.recursiveTree(permissionList)
      })
    },
    //递归序列权限列表
    recursiveTree (list) {
      let permissionList = []
      if (!list || list.length === 0) return []
      for (let i = 0; i < list.length; i++) {
        const sonPermission = list[i]
        permissionList.push({
          title: sonPermission.name,
          key: sonPermission.id,
          children: this.recursiveTree(sonPermission.sonPermissionList)
        })
      }
      return permissionList
    },
    //查找匹配上的权限id，返回它的自权限数组
    recursiveQuery (id, treeData) {
      let PermissionList = null
      for (let i = 0; i < treeData.length; i++) {
        const item = treeData[i];
        if (item.key === id) return item.children || []

        if (item.children && item.children.length > 0) {
          PermissionList = this.recursiveQuery(id, item.children)
          if (PermissionList) return PermissionList
        }
      }
    },
    //添加父权限id
    addparentId (id, treeData) {
      let parentId = null
      for (let i = 0; i < treeData.length; i++) {
        const item = treeData[i];
        if (item.id === id) return item.parentId || 'null'

        if (item.sonPermissionList && item.sonPermissionList.length > 0) {
          parentId = this.addparentId(id, item.sonPermissionList)
          if (parentId || parentId === 'null') return parentId
        }
      }
    },
    //根据权限解析出需要的ID
    parsingRoleId (list) {
      let permissionList = []
      for (let i = 0; i < list.length; i++) {
        const id = list[i].id
        list.push(...(list[i].sonPermissionList || []))
        let PermissionList = this.recursiveQuery(id, this.treeData)
        if (PermissionList.length === (list[i].sonPermissionList || []).length) {
          permissionList.push(id)
        }
      }
      return permissionList
    },

    submit () {
      let permissionIdList = []
      for (let index = 0; index < this.form.permissionIdList.length; index++) {
        const list = this.form.permissionIdList[index];
        let parentId = this.addparentId(list, this.originData)
        if (parentId && parentId !== 'null') permissionIdList.push(parentId)
        permissionIdList.push(list)
      }
      permissionIdList = Array.from(new Set(permissionIdList))
      let method = ''
      let data = {
        name: this.form.name,
        permissionIdList: permissionIdList,
      }
      if (this.roleId) {
        method = 'put'
        data.id = this.roleId
      } else {
        method = 'post'
      }
      this.$axios({
        url: '/role',
        method: method,
        loadingEl: this.$el,
        cancel: {
          _self: this
        },
        data: data
      }).then(res => {
        this.$router.push({ path: '/setting/permission' })
        this.$message.success(this.roleId ? '修改成功' : '创建成功')
      })
    }
  },
}

</script>
<style scoped lang='less'>
.modifyPermission {
  // height: 100%;
  // overflow: auto;
}
</style>